package com.gkt.ec.ws.activity.service;

import com.gkt.ec.ws.activity.AppConstant;
import com.gkt.ec.ws.activity.dao.CustomerActivityDao;
import com.gkt.ec.ws.activity.model.domain.CustomerActivityEntity;
import com.gkt.ec.ws.activity.model.domain.MarketActivityEntity;
import com.gkt.library.commons.shared.utils.SMSInvoker;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Huzl
 * @version 1.0.0
 */
@Service
public class CustomerActivityService {
    public static final int VERIFY_CODE_LENGTH = 10;
    public static final String GKTECQRCODE = "gktecqrcode_";
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CustomerActivityDao customerActivityDao;

    public MarketActivityEntity getActivity(Long activityId){
        return customerActivityDao.getActivity(activityId);
    }

    /**
     * 根据活动ID查询客户参与的活动记录
     * @param customerActivityId
     * @return
     */
    public CustomerActivityEntity getCustomerActivity(Long customerActivityId){
        return customerActivityDao.getCustomerActivity(customerActivityId);
    }

    public CustomerActivityEntity getCustomerActivityByPhone(Long customerActivityId,
                                                             String phone){
        return customerActivityDao.getCustomerActivityByPhone(customerActivityId, phone);
    }

    public CustomerActivityEntity getCustomerActivityByVerifyCode(String verifyCode){
        return customerActivityDao.getCustomerActivityByVerifyCode(verifyCode);
    }

    /**
     * 客户确认参与活动,生成验证码信息并发送短信
     * @param customerActivityEntity
     */
    @Transactional
    public void confirmAttendActivity(MarketActivityEntity activityEntity ,
                                      CustomerActivityEntity customerActivityEntity)throws IOException{
        String verifyCode;
        for(;;){
            verifyCode = RandomStringUtils.randomNumeric(VERIFY_CODE_LENGTH);
            CustomerActivityEntity existCustomerActivityEntity = getCustomerActivityByVerifyCode(verifyCode);
            if(existCustomerActivityEntity == null)
                break;
        }
        if(AppConstant.Verify_Type.QR_CODE.equals(activityEntity.getVerifyType())){
            verifyCode = GKTECQRCODE + verifyCode;
        }
        customerActivityDao.updateVerifyCode(customerActivityEntity.getId(),verifyCode);
        customerActivityEntity.setVerifyCode(verifyCode);

        customerActivityDao.increaseAttendUserCount(activityEntity.getId());
        activityEntity.setAttendUserCount(activityEntity.getAttendUserCount()+1);

        sendSms(activityEntity, customerActivityEntity);
        logger.info("confirmAttendActivity success activityId:{},name:{},customerActivityId:{},tel:{},verifyCode:{}",
                activityEntity.getId(),activityEntity.getActivityName(),
                customerActivityEntity.getCustomerTel(),verifyCode);
    }

    /**
     * 商家确认使用验证码
     * @param customerActivityEntity
     * @param companyId
     */
    @Transactional
    public void companyVerify(CustomerActivityEntity customerActivityEntity,Long companyId){
        customerActivityDao.updateCompanyVerifyStatus(customerActivityEntity.getId(),
                AppConstant.ActivitySmsVerifyStatus.COMPANY_VERIFY,companyId);
        logger.info("companyVerify success activityId:{},customerActivityId:{},companyId:{}",
                customerActivityEntity.getActivityId(),customerActivityEntity.getId(),companyId);
    }

    /**
     * 活动是否包含商家
     * @param activityId
     * @param companyId
     * @return
     */
    public boolean isExistActivity(Long activityId,Long companyId){
        return customerActivityDao.getCompanyActivity(activityId, companyId) != null;
    }

    private void sendSms(MarketActivityEntity activityEntity ,
                        CustomerActivityEntity customerActivityEntity)throws IOException{
        String smsContent = buildSmsContent(activityEntity, customerActivityEntity);
        String errorCode = SMSInvoker.yixinxiSendMsg(customerActivityEntity.getCustomerTel(), smsContent);

        logger.info("CustomerActivityService sendSms activityId:{},customerActivityId:{},tel:{},smsContent:{} " +
                "| errorCode={}",
                customerActivityEntity.getActivityId(),customerActivityEntity.getId(),
                customerActivityEntity.getCustomerTel(), smsContent,errorCode);
        if(!errorCode.equals("0")){
            throw new RuntimeException("wrong error code while sending sms,error code:" + errorCode);
        }
    }

    private String buildSmsContent(MarketActivityEntity activityEntity ,
                                   CustomerActivityEntity customerActivityEntity){
        Map<String,String> values = new HashMap<String, String>();

        values.put("activityName",activityEntity.getActivityName());
        values.put("attendUserCount",String.valueOf(activityEntity.getAttendUserCount()));
        values.put("vehicleLicense",customerActivityEntity.getVehicleLicense());
        values.put("customerTel", customerActivityEntity.getCustomerTel());
        values.put("activityId", String.valueOf(customerActivityEntity.getActivityId()));
        values.put("customerId",customerActivityEntity.getCustomId());
        values.put("verifyCode",customerActivityEntity.getVerifyCode());
        values.put("customerActivityId",String.valueOf(customerActivityEntity.getId()));
        //替换活动url中的参数
        String url = replaceTemplate(activityEntity.getActivityUrl(),values);
        values.put("url",url);

        String smsContent = activityEntity.getAttendNotifySmsTemplate();
        return replaceTemplate(smsContent,values);
    }

    private String replaceTemplate(String str,Map<String,String> variables){
        if(str == null)return null;
        for(Map.Entry<String,String> entry:variables.entrySet()){
            if(!str.contains("{") && !str.contains("}"))
                return str;
            if(entry.getValue() != null)
                str = StringUtils.replace(str, "{" + entry.getKey() + "}", entry.getValue());
        }
        return str;
    }



}
